<template>
  <div class="workpart-container">
    <div style="
        padding: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      ">
      <div style="display: flex; align-items: center">
        <el-button type="primary" icon="el-icon-document-add" :disabled="taskSoureDisabled" size="small" @click="addPart">添加零件</el-button>
        <el-tag style="margin-left: 10px">种类：0</el-tag>
        <el-tag style="margin: 0 10px">数量：0</el-tag>
        <el-button type="primary" size="small" @click="stockLayout">排样</el-button>
        <el-button type="primary" size="small" @click="createBus">飞排</el-button>
        <el-button type="primary" size="small" @click="createBus">飞传</el-button>
        <el-button type="warning" size="small" @click="reset">列表重置</el-button>
      </div>
      <div style="display: flex; align-items: center">
        
        <!-- <el-button type="danger" icon="el-icon-document-add" size="small" @click="createBus">删除</el-button> -->
      </div>
      <div>
        <el-button-group>
          <el-tooltip class="item" effect="dark" content="列表" placement="top-end">
            <el-button size="mini" :type="isList ? 'primary' : ''" @click="isList = true" icon="el-icon-s-operation"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="缩略图" placement="top-end">
            <el-button size="mini" :type="!isList ? 'primary' : ''" @click="isList = false" icon="el-icon-s-grid"></el-button>
          </el-tooltip>
        </el-button-group>
      </div>
    </div>
    <div :class="!isList ? 'workpartthumbnail-container' : ''">
      <el-table :data="tableData" style="width: 100%" height="80vh" ref="filterTable" border @selection-change="handleSelectionChange" v-loading="loading">
        <el-table-column type="selection" width="55" align="center" :selectable='isDisabled'></el-table-column>
        <el-table-column width="100" trigger="click" align="center" show-overflow-tooltip fixed="left">
          <template slot="header">
            <header-filter title="零件名称" :current-sort="currentSort" props="name" :filter-change="filterChange" :filters="filters.name" />
          </template>
          <template slot-scope="scope">{{ scope.row.part ? scope.row.part.name : '' }}</template>
        </el-table-column>
        <el-table-column width="140" align="center">
          <template slot="header">
            <header-filter title="待排-在排-已排" :current-sort="currentSort" props="processing" :filter-change="filterChange" :filters='[
              {text: "待排", value: "待排"},{text: "在排", value: "在排"},{text: "已排", value: "已排"}]' />
          </template>
          <template slot-scope="scope">
            <el-tag type="info">{{ scope.row.waitQty || 0 }}</el-tag>
            <el-tag style="margin:0 4px;">{{ scope.row.processingQty || 0 }}</el-tag>
            <el-tag type="success">{{ scope.row.processedQty || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="缩略图" align="center" width="100">
          <template slot-scope="scope">
            <el-image v-if="scope.row.part" style="width: 80px; height: 80px" :src="getAssteImage(scope.row.part.previewUrl)" fit="contain" :preview-src-list="[getAssteImage(scope.row.part.previewUrl)]">
            </el-image>
          </template>
        </el-table-column>

        <el-table-column width="100" align="center">
          <template slot="header">
            <header-filter title="材料" :current-sort="currentSort" sortable props="material" :filter-change="filterChange" :filters="filters.material" />
          </template>
          <template slot-scope="scope">{{ scope.row.part ? scope.row.part.material : '' }}</template>
        </el-table-column>
        <el-table-column width="120" align="center">
          <template slot="header">
            <header-filter title="厚度(mm)" :current-sort="currentSort" sortable props="thick" :filter-change="filterChange" :filters="filters.thick" />
          </template>
          <template slot-scope="scope">
            {{ scope.row.part ? scope.row.part.thick : '' }}
          </template>
        </el-table-column>
        <el-table-column width="100" align="center">
          <template slot="header">
            <header-filter title="数量" :current-sort="currentSort" sortable props="bcQty" :filter-change="filterChange" :filters="filters.bcQty" />
          </template>
          <template slot-scope="scope">
            {{ scope.row.bcQty || 0 }}
          </template>
        </el-table-column>
        <el-table-column width="150" align="center">
          <template slot="header">
            <header-filter title="尺寸(X*Y)(mm)" :current-sort="currentSort" sortable props="spec" :filter-change="filterChange" :filters="filters.spec" />
          </template>
          <template slot-scope="scope">
            {{ scope.row.specs}}
          </template>
        </el-table-column>
        <!-- <el-table-column label="图纸" align="center" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.part ? scope.row.part.drawingUrl : '' }}</template>
        </el-table-column> -->
        <el-table-column label="来料加工" align="center" >
          <template slot-scope="scope">
            <el-tag v-if="!scope.row.materialFlag">是</el-tag>
            <el-tag type="success" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否锁定" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isLocked == 0">否</el-tag>
            <el-switch v-if="scope.row.isLocked == 1" v-model="scope.row.isLocked==1?true:false" inactive-text="解锁" @change="()=>colunmUnLock(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column width="180" label="待排产-待切-在切-已切" align="center">
          <template slot-scope="scope">
            <el-tag type="info">{{ scope.row.processedQty || 0 }}</el-tag>
            <el-tag style="margin-left:4px;" type="warning">0</el-tag>
            <el-tag style="margin-left:4px;">0</el-tag>
            <el-tag style="margin-left:4px;" type="success">0</el-tag>
          </template>
        </el-table-column>
        <el-table-column width="100" align="center">
          <template slot="header">
            <header-filter title="优先级" :current-sort="currentSort" props="prioritys" :filter-change="filterChange" :filters="filters.priority" />
          </template>
          <template slot-scope="scope">
            <el-tag v-if="scope.row.priority == 0">普通级</el-tag>
            <el-tag type="danger" v-if="scope.row.priority == 1">最高级</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" style="color:red;" v-if="!taskSoureDisabled" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      </el-table>
    </div>
    <div class="list-content scrollbar" v-if="!isList" style="max-height:80vh">
      <div class="list-group" v-for="(item, index) in tableData" :key="index">
        <div class="list-item">
          <div class="list-imgs">
            <el-image v-if="item.part" style="width: 100%; height: 100%" :src="getAssteImage(item.part.previewUrl)" fit="contain" :preview-src-list="[getAssteImage(item.part.previewUrl)]">
            </el-image>
          </div>
          <div class="list-item-title">{{ item.name }}</div>
          <div class="list-item-info">材料：{{ item.part ? item.part.material : '' }}</div>
          <div class="list-item-info">数量：{{ item.part ? item.part.length : '' }}</div>
        </div>
      </div>
    </div>
    <div class="pagination">
      <el-pagination layout="sizes,total, prev, pager, next, jumper" :current-page="query.page" :page-size="query.pageSize" :page-sizes="[10, 50, 100, 150, 200]" @size-change="handleSizeChange" :total="total" @current-change="handlePageChange"></el-pagination>
    </div>
    <el-dialog title="添加零件" :visible.sync="addOpen" width="600px" append-to-body :close-on-click-modal="false" top="1.5%">
      <el-form ref="workform" :model="uploadFrom" :rules="uploadWork" label-width="110px" label-position="left">
        <el-form-item label="选择一个作业" prop="name">
          <el-radio-group v-model="taskId">
            <el-radio :label="item.id" :key="index" v-for="(item, index) in checkTasks">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-debounce-click="submitAdd">确 定</el-button>
        <el-button @click="addOpen = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择板材" :visible.sync="openScheduling" width="90%" append-to-body :close-on-click-modal="false" top="1.5%">
      <workscheduling :part-list="multipleSelection" :close.sync="openScheduling" />
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import fileUpload from '@/components/imgUpload/fileUpload.vue';
import HeaderFilter from '@/components/headerFilter/HeaderFilter.vue';
import Workscheduling from './Workscheduling.vue';
import { uniq, findIndex, clone, orderBy, isString, isPlainObject } from 'lodash';
import globalJs from '@/utils/global';
export default {
  name: 'Workpart',
  components: { fileUpload, Workscheduling, HeaderFilter },
  data() {
    return {
      currentSort: '',
      keyword: '',
      tableData: [],
      sourceData: [],
      openScheduling: false,
      loading: false,
      isList: true,
      addOpen: false,
      uploadWork: {},
      uploadFrom: {},
      fileUrl: '',
      taskId: '',
      filters: {
        name: [],
        material: [],
        thick: [],
        bcQty: [],
        spec: [],
        priority: []
      },
      filterVals: {
        processing: [],
        name: [],
        material: [],
        thick: [],
        bcQty: [],
        spec: [],
        priority: [],
      },
      query: {
        page: 1,
        pageSize: 50
      },
      total: 0,
      multipleSelection: [],
      taskSoureDisabled:true
    };
  },
  computed: {
    ...mapState({
      checkTaskIds: (state) => state.app.checkTaskIds,
      checkTasks: (state) => state.app.checkTasks,
      CADpartPath: (state) => state.app.CADpartPath,
      uploadPartInfo: (state) => state.resource.uploadPartInfo,
      partRefreshList: (state) => state.app.partRefreshList,
      uploadLayoutInfo: (state) => state.resource.uploadLayoutInfo,
      CADLayoutPath: (state) => state.app.CADLayoutPath,
    }),
  },
  filters: {
    formDate: (val) => {
      return global.getdate1(val);
    },
  },
  watch: {
    checkTaskIds: {
      deep: true,
      handler: function (val) {
        if (val.length > 0) {
          this.initAjaxMethod();
        }else{
          this.resetSearch();
          this.orignData = [];
          this.sourceData = [];
          this.total = 0;
          this.tableData = [];
        }
        this.getTaskOrgin()
      },
    },
    CADpartPath: {
      deep: true,
      handler: function (val) {
        if (val.length > 0) {
          this.uploadCADPartMethod(val);
        }

      },
    },
    partRefreshList: {
      deep: true,
      handler: function (val) {
        this.initreset();
      },
    },
    CADLayoutPath: {
      deep: true,
      handler: function (val) {
        this.initreset();
      },
    },
  },
  mounted() {
    if (this.checkTaskIds.length > 0) {
      this.initAjaxMethod();
      this.getTaskOrgin()
    }
  },
  methods: {
    initAjaxMethod() {
      this.loading = true;
      this.$http
        .get(this.$API.WORK_PART + '?' + this.checkTaskIds.map(o => 'taskIds=' + o).join('&'))
        .then((res) => {
          this.loading = false;
          // let list = [
          //   { BcQty: 200, Priority: 0, part: { name: '1', id: '00270e75-233d-4e29-9453-b34208f7aab0', material: 'GP520', pieceWeight: 1, spec: '10*90' } },
          //   { BcQty: 200, Priority: 0, part: { name: '2', id: '00270e75-233d-4e29-9453-b34208f7aab0', material: 'GP521', pieceWeight: 1, spec: '10*90' } },
          // ];
          let list = Array.isArray(res.data) ? res.data : [];
          let name = [], material = [], thick = [], bcQty = [], spec = [], priority = [];
          list.forEach(item => {
            if (item.part) {
              item.specs=item.part.width+'*'+item.part.length;
              name.push(item.part.name);
              material.push(item.part.material);
              thick.push(item.part.thick);
              bcQty.push(item.bcQty);
              spec.push(item.specs);
              priority.push(item.priority);
            }
          });
          this.filters.name = uniq(name).map(o => { return { text: o, value: o } });
          this.filters.material = uniq(material).map(o => { return { text: o, value: o } });
          this.filters.thick = uniq(thick).map(o => { return { text: o, value: o } });
          this.filters.bcQty = uniq(bcQty).map(o => { return { text: o, value: o } });
          this.filters.spec = uniq(spec).map(o => { return { text: o, value: o } });
          this.filters.priority = uniq(priority).map(o => { return { text: o, value: o } });
          this.orignData = list;
          this.sourceData = list;
          this.query.page = 1; 
          this.total = list.length;
          this.limitMethod();
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    getTaskOrgin(){
      if(this.checkTaskIds.length != 1){
        this.taskSoureDisabled=true;
        return;
      }
      this.$http
        .get(this.$API.WORK_TASK + '/'+this.checkTaskIds[0]).then(res=>{
          this.taskSoureDisabled=res.data.taskSoure == 1?false:true;
        })
    },
    colunmUnLock(data){
      let layout=this.uploadLayoutInfo,isLocalLayout=false;
      let parmesData=[{taskId:data.taskId,partId:data.part.id}];
      if (layout && isPlainObject(layout) && Array.isArray(layout.Parts) && layout.Parts.length>0) {
          let cIndex=findIndex(layout.Parts,o=>o.partId==data.part.id);
          if(cIndex>=0){
            parmesData=layout.Parts.map(o=>{return {taskId:o.taskId,partId:o.partId}});
            isLocalLayout=true;
          }
      }
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.SET_LAYOUT_UNLOCK, parmesData)
        .then((res) => {
          loading.close();
          this.$message.success('操作成功!');
          if(isLocalLayout){
            this.$store.dispatch('resource/setUploadLayoutInfo', null);
          }
          this.initAjaxMethod();
        })
        .catch((err) => {
          loading.close();
        });
    },
    filterChange(code, type, value) {
      if (type === 'checkBox') {
        if (code === 'processing') {
          this.filterVals.processing = value;
        } else if (code === 'name') {
          this.filterVals.name = value;
        } else if (code === 'material') {
          this.filterVals.material = value;
        } else if (code === 'thick') {
          this.filterVals.thick = value;
        } else if (code === 'bcQty') {
          this.filterVals.bcQty = value;
        } else if (code === 'spec') {
          this.filterVals.spec = value;
        } else if (code === 'priority') {
          this.filterVals.priority = value;
        }
        // console.log('this.filterVals',this.filterVals); 
        this.filterHandler();
      } else if (type === 'sort') {
        this.currentSort = code;
        if (code === 'material') {
          this.sourceData = orderBy(clone(this.sourceData), 'part.material', value);
        } else if (code === 'thick') {
          this.sourceData = orderBy(clone(this.sourceData), 'part.thick', value);
        } else if (code === 'bcQty') {
          this.sourceData = orderBy(clone(this.sourceData), 'bcQty', value);
        } else if (code === 'spec') {
          this.sourceData = orderBy(clone(this.sourceData), 'specs', value);
        }
        this.limitMethod();
      }

    },
    filterHandler() {
      let processings = [], names = [], materials = [], thicks = [], bcQtys = [], specs = [], prioritys = [];
      let { processing, name, material, thick, bcQty, spec, priority } = this.filterVals;
      if (processing.length > 0) {
        let waitQty = findIndex(processing, o => o === '待排');
        let processingQty = findIndex(processing, o => o === '在排');
        let processedQty = findIndex(processing, o => o === '已排');
        this.orignData.forEach(item => {
          if ((waitQty > -1 && item.waitQty > 0) || (processingQty > -1 && item.processingQty > 0) || (processedQty > -1 && item.processedQty > 0)) {
            processings.push(item)
          }
        })
      } else {
        processings = this.orignData;
      }
      // console.log('processings',processings);
      if (name.length > 0) {
        processings.forEach(item => {
          let namesIndex = findIndex(name, o => o == item.part.name);
          if (namesIndex > -1) {
            names.push(item);
          }
        });
      } else {
        names = processings;
      }

      if (material.length > 0) {
        names.forEach(item => {
          let materialsIndex = findIndex(material, o => o == item.part.material);
          if (materialsIndex > -1) {
            materials.push(item);
          }
        });
      } else {
        materials = names;
      }

      if (thick.length > 0) {
        materials.forEach(item => {
          let thicksIndex = findIndex(thick, o => o == item.part.thick);
          if (thicksIndex > -1) {
            thicks.push(item);
          }
        });
      } else {
        thicks = materials;
      }

      if (bcQty.length > 0) {
        thicks.forEach(item => {
          let bcQtysIndex = findIndex(bcQty, o => o == item.bcQty);
          if (bcQtysIndex > -1) {
            bcQtys.push(item);
          }
        });
      } else {
        bcQtys = thicks;
      }

      if (spec.length > 0) {
        bcQtys.forEach(item => {
          let specsIndex = findIndex(spec, o => o == item.specs);
          if (specsIndex > -1) {
            specs.push(item);
          }
        });
      } else {
        specs = bcQtys;
      }

      if (priority.length > 0) {
        specs.forEach(item => {
          let prioritysIndex = findIndex(priority, o => o == item.part.priority);
          if (prioritysIndex > -1) {
            prioritys.push(item);
          }
        });
      } else {
        prioritys = specs;
      }

      this.sourceData = prioritys;
      this.total = prioritys.length;
      this.handlePageChange(1);
    },
    createBus() { },
    async addPart() {
      if (!Array.isArray(this.checkTasks) || this.checkTasks.length == 0) {
        return this.$message.error('请选择一个作业');
      }
      if (this.checkTasks.length > 1) {
        return this.$message.error('只能选择一个作业,请勿多选');
      }
      this.taskId = this.checkTasks[0].id;
      let isLine = await this.$hubClient.sendlsClientOnline('cad');
      if (this.uploadPartInfo && isString(this.uploadPartInfo)) {
        this.$confirm('当前CAD有零件在制作中,请完成后再处理！', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning',
        });
        if (isLine === false) {
          this.$hubClient.sendOpenClient();
        }
        return false;
      }
      // 保存零件数据
      this.$store.dispatch('resource/setUploadPartInfo', this.taskId);
      // 启动CAD
      if (isLine === true) {
        this.$hubClient.sendCreatePart(this.taskId);
        store.dispatch('resource/setUploadPartInfo', null);
      } else {
        this.$hubClient.sendOpenClient();
      }
      this.$message.success('数据已发送,请等待CAD处理');
    },
    submitAdd() {
      if (!this.taskId) return this.$message.error('请选择一个作业');
      this.$hubClient.sendCreatePart(this.taskId);
      this.$message.success('数据已发送');
      this.addOpen = false;
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async stockLayout(a, b) {
      if (this.uploadLayoutInfo && isPlainObject(this.uploadLayoutInfo)) {
        this.$confirm('当前CAD正在排样中,请完成后再操作！', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning',
        });
        return false;
      }
      if (this.multipleSelection.length == 0) return this.$message.error('请选择一个零件');
      let cIndex = findIndex(this.multipleSelection, o => o.isLocked == 1);
      if (cIndex >= 0) return this.$message.error('选中零件中,有已锁定项目,请重新选择！');
      this.openScheduling = true;
    },

    //重置
    reset() {
      this.resetSearch();
      this.sourceData = this.orignData;
      this.limitMethod();
    },
    initreset() {
      this.resetSearch();
      this.initAjaxMethod()
    },
    resetSearch(){
      this.$store.dispatch('app/clearTableHeaderFilter');
      this.currentSort = '';
      this.query.page = 1;
    },
    isDisabled(row, index) {
      if (row.isLocked > 0) {
        return false
      } else {
        return true
      }
    },
    delAllSelection() {
      let arr = [];
      if (this.multipleSelection.length <= 0) {
        this.$message({
          type: 'error',
          message: '请选择活动',
        });
        return false;
      } else {
        this.multipleSelection.forEach((item) => {
          arr.push(item.id);
        });
        this.handleDelete(arr.join(','), this.$API.ZHACTIVE_ALL_DEL);
      }
    },
    changeStatus(item) {
      console.log('item', item);
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.ZHACTIVE_STATUS, {
          id: item.id,
          status_show: item.status_show_switch == true ? 0 : 1,
        })
        .then((res) => {
          loading.close();
          if (res.code == 1) {
            this.$message.success('操作成功!');
            this.initAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(res.msg);
        });
    },
    uploadCADPartMethod(urls) {
      this.$http
        .post(this.$API.WORK_PART + '/batch', urls)
        .then((res) => {
          this.$confirm('零件任务上传成功!', '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'success',
          })
          this.initAjaxMethod();
        });
    },
    uploadCADLayoutMethod() {
      this.$http
        .post(this.$API.GET_LAYOUT, urls)
        .then((res) => {
          this.$message.success('CAD排样提交成功');
          this.initreset();
        });
    },
    //删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const loading = this.$loading({ text: '加载中...' });
        this.$http.del(this.$API.WORK_PART + '/id?id=' + row.id).then((res) => {
          loading.close();
          this.$message.success('删除成功');
          this.initAjaxMethod();
        }).catch(e => { loading.close(); })
      });
    },
    //点击第几页
    handlePageChange(currentPage) {
      this.query.page = currentPage;
      this.limitMethod();
    },
    //点击第几页
    handleSizeChange(currentPage) {
      this.query.pageSize = currentPage;
      this.limitMethod();
    },
    limitMethod() {
      let list = [], { page, pageSize } = this.query;
      for (let i = 0; i < this.sourceData.length; i++) {
        if (i >= ((page - 1) * pageSize) && i < (page * pageSize)) {
          list.push(this.sourceData[i]);
        }
      }
      this.tableData = list;
    },
    getAssteImage(url) {
      return url && isString(url) ? (globalJs.isAbsolutePath(url) ? url : this.$API.ASSERT_SERVER_URL + url) : '';
    }
  },
};
</script>
<style lang="less">
.workpart-container {
  .workpartthumbnail-container {
    .el-table {
      height: 72px !important;
    }

    .el-table__body-wrapper {
      height: 16px !important;

      .el-table__body {
        height: 0 !important;
      }

      .el-table__empty-block {
        height: 0 !important;
        min-height: 0 !important;
      }
    }
  }

  .table-container {
    height: 75vh;
  }
}
</style>
